/**
 * Huisou.com Inc.
 * Copyright (c) 2011-2012 All Rights Reserved.
 */

package com.chenzehe.zdmya.action;

import static com.chenzehe.java.core.Status.STATUS_NORMAL;
import static com.chenzehe.zdmya.Constants.SESSION_CHECKCODE;
import static com.chenzehe.zdmya.Constants.SESSION_USER;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.util.WebUtils;

import com.chenzehe.java.core.Constants;
import com.chenzehe.java.core.freemarker.HtmlPathHelp;
import com.chenzehe.java.core.orm.Page;
import com.chenzehe.java.core.orm.PageRequest;
import com.chenzehe.java.core.utils.WebUtil;
import com.chenzehe.zdmya.domain.Baoliao;
import com.chenzehe.zdmya.domain.Collection;
import com.chenzehe.zdmya.domain.Coupon;
import com.chenzehe.zdmya.domain.Fx;
import com.chenzehe.zdmya.domain.Jy;
import com.chenzehe.zdmya.domain.Message;
import com.chenzehe.zdmya.domain.OperatePoint;
import com.chenzehe.zdmya.domain.User;
import com.chenzehe.zdmya.service.IBaoliaoService;
import com.chenzehe.zdmya.service.ICollectionService;
import com.chenzehe.zdmya.service.IContentService;
import com.chenzehe.zdmya.service.ICouponService;
import com.chenzehe.zdmya.service.IFxService;
import com.chenzehe.zdmya.service.IJyService;
import com.chenzehe.zdmya.service.IMessageService;
import com.chenzehe.zdmya.service.IUserService;

/**
 * @description
 * 
 * @author chenzehe
 * @email hljuczh@163.com
 * @create 2012-8-14 下午08:14:05
 */
@Controller
public class UserAction extends BaseAction {
	@Resource
	IUserService userService;
	@Resource
	IMessageService messageService;
	@Resource
	ICollectionService collectionService;
	@Resource
	IContentService contentService;
	@Resource
	IFxService fxService;
	@Resource
	IJyService jyService;
	@Resource
	ICouponService couponService;
	@Resource
	IBaoliaoService baoliaoService;

	@RequestMapping(value = "/user/jy.html")
	public String userJy(HttpServletRequest request, ModelMap model) {
		User user = (User) WebUtils.getSessionAttribute(request, SESSION_USER);
		model.addAttribute("user", user);
		model.addAttribute("jyCurrent", "current");

		int pageNo = WebUtil.getInt(request, "p", 1);
		int pageSize = WebUtil.getInt(request, "pageSize", 2);
		PageRequest pageRequest = new PageRequest(pageNo, pageSize);
		Page<Jy> pageJy = jyService.queryJyByUser(pageRequest, user.getId());
		model.addAttribute("pageJy", pageJy);

		return HtmlPathHelp.getHtmlPathFront("user_jy");
	}

	@RequestMapping(value = "/user/baoliao.html")
	public String userBaoliao(HttpServletRequest request, ModelMap model) {
		User user = (User) WebUtils.getSessionAttribute(request, SESSION_USER);
		model.addAttribute("user", user);
		model.addAttribute("baoliaoCurrent", "current");

		int pageNo = WebUtil.getInt(request, "p", 1);
		int pageSize = WebUtil.getInt(request, "pageSize", 2);
		PageRequest pageRequest = new PageRequest(pageNo, pageSize);
		Page<Baoliao> pageBaoliao = baoliaoService.queryBaoliaoByUser(
				pageRequest, user.getId());
		model.addAttribute("pageBaoliao", pageBaoliao);

		return HtmlPathHelp.getHtmlPathFront("user_baoliao");
	}

	@RequestMapping(value = "/user/deletecollection.html")
	public String deleteCollection(HttpServletRequest request, ModelMap model) {
		User user = (User) WebUtils.getSessionAttribute(request, SESSION_USER);
		int id = WebUtil.getInt(request, "id");
		int p = WebUtil.getInt(request, "p", 1);
		int type = WebUtil.getInt(request, "t",
				Collection.CollectionType.CONTENT.type());
		collectionService.deleteByIdAndUser(id, user.getId());
		return "redirect:/user/collection.html?type=" + type + "&p=" + p;

	}

	@RequestMapping(value = "/user/collection.html")
	public String userCollection(HttpServletRequest request, ModelMap model) {
		User user = (User) WebUtils.getSessionAttribute(request, SESSION_USER);
		model.addAttribute("user", user);
		model.addAttribute("collectionCurrent", "current");
		model.addAttribute("collectionCurrentUL", "curent_menu");
		int type = WebUtil.getInt(request, "t",
				Collection.CollectionType.CONTENT.type());
		model.addAttribute("type", type);
		if (type == Collection.CollectionType.CONTENT.type()) {
			model.addAttribute("collectoinCurrentLiContent", "subCurrent");
		} else if (type == Collection.CollectionType.FX.type()) {
			model.addAttribute("collectoinCurrentLiFx", "subCurrent");
		} else if (type == Collection.CollectionType.JY.type()) {
			model.addAttribute("collectoinCurrentLiJy", "subCurrent");
		}
		int pageNo = WebUtil.getInt(request, "p", 1);
		int pageSize = WebUtil.getInt(request, "pageSize", 2);
		PageRequest pageRequest = new PageRequest(pageNo, pageSize);
		Page<Collection> pageCollection = collectionService.queryByUserAndType(
				pageRequest, user.getId(), type);
		model.addAttribute("pageCollection", pageCollection);

		return HtmlPathHelp.getHtmlPathFront("user_collection");

	}

	@RequestMapping(value = "/user/deletecomment.html")
	public String deleteComment(HttpServletRequest request, ModelMap model) {
		User user = (User) WebUtils.getSessionAttribute(request, SESSION_USER);
		int id = WebUtil.getInt(request, "id");
		int p = WebUtil.getInt(request, "p", 1);
		int type = WebUtil.getInt(request, "t",
				Message.MessageType.CONTENT.type());
		messageService.deleteByIdAndUser(id, user.getId());
		return "redirect:/user/comment.html?t=" + type + "&p=" + p;

	}

	@RequestMapping(value = "/user/comment.html")
	public String userComment(HttpServletRequest request, ModelMap model) {
		User user = (User) WebUtils.getSessionAttribute(request, SESSION_USER);
		model.addAttribute("user", user);
		int type = WebUtil.getInt(request, "t",
				Message.MessageType.CONTENT.type());
		model.addAttribute("type", type);
		if (type == Message.MessageType.CONTENT.type()) {
			model.addAttribute("commentCurrentLiContent", "subCurrent");
		} else if (type == Message.MessageType.FX.type()) {
			model.addAttribute("commentCurrentLiFx", "subCurrent");
		} else if (type == Message.MessageType.JY.type()) {
			model.addAttribute("commentCurrentLiJy", "subCurrent");
		}
		int pageNo = WebUtil.getInt(request, "p", 1);
		int pageSize = WebUtil.getInt(request, "pageSize", 10);
		PageRequest pageRequest = new PageRequest(pageNo, pageSize);
		pageRequest.setOrderBy("id");
		pageRequest.setOrderDir(PageRequest.Sort.DESC);
		Page<Message> messages = messageService.queryByUserIdAndType(
				pageRequest, user.getId(), type);
		model.addAttribute("messages", messages);
		model.addAttribute("commentCurrent", "current");
		model.addAttribute("commentCurrentUL", "curent_menu");
		return HtmlPathHelp.getHtmlPathFront("user_comment");

	}

	@RequestMapping(value = "/user/info.html")
	public String userInfo(HttpServletRequest request, ModelMap model) {
		User user = (User) WebUtils.getSessionAttribute(request, SESSION_USER);
		model.addAttribute("user", user);
		String message = WebUtil.getString(request, "m");
		model.addAttribute("message", message);
		model.addAttribute("infoCurrent", "current");
		return HtmlPathHelp.getHtmlPathFront("user_info");

	}

	@RequestMapping(value = "/user/updateuserinfo.html")
	public String updatePassword(HttpServletRequest request, ModelMap model) {
		String pass_1 = WebUtil.getString(request, "pass_1");
		String pass_2 = WebUtil.getString(request, "pass_2");
		String username = WebUtil.getString(request, "username");
		User user = (User) WebUtils.getSessionAttribute(request, SESSION_USER);
		User updateUser = new User();
		updateUser.setId(user.getId());
		String m = "failed !";
		if (StringUtils.isNotBlank(pass_1) && StringUtils.isNotBlank(pass_2)) {
			if (pass_1.equals(pass_2)) {
				updateUser.setPassword(pass_1);
				if (StringUtils.isNotBlank(username)) {
					updateUser.setUsername(username);
					userService.updateUsernameAndPassword(updateUser);
					user.setUsername(username);
				} else {
					userService.updatePassword(updateUser);
				}
				user.setPassword(pass_1);
				m = "success !";
			}
		} else if (StringUtils.isNotBlank(username)) {
			updateUser.setUsername(username);
			userService.updateUsername(updateUser);
			user.setUsername(username);
			m = "success !";
		}
		WebUtils.setSessionAttribute(request, SESSION_USER, user);
		return "redirect:/user/info.html?m=" + m;

	}

	@RequestMapping(value = "/user/uploaduserimg.html")
	public String uploadUserImg(
			@RequestParam(value = "filedata", required = true) MultipartFile file,
			HttpServletResponse response, HttpServletRequest request,
			ModelMap model) throws Exception {
		if (file != null && file.getSize() > 0) {
			User user = (User) WebUtils.getSessionAttribute(request,
					SESSION_USER);
			String imgpath = userService.uploadAvatar(file, user);
			user.setAvatar(imgpath);
			WebUtils.setSessionAttribute(request, SESSION_USER, user);
		}
		return "redirect:/user/info.html";
	}

	@RequestMapping(value = "/user/index.html")
	public String userIndex(HttpServletRequest request, ModelMap model) {
		User user = (User) WebUtils.getSessionAttribute(request, SESSION_USER);
		model.addAttribute("user", user);

		model.addAttribute("collectionNum",
				collectionService.queryCollectionNum(user.getId()));
		model.addAttribute("contentNum",
				contentService.queryNumByUser(user.getId()));
		model.addAttribute("fxNum", fxService.queryNumByUser(user.getId()));
		model.addAttribute("jyNum", jyService.queryNumByUser(user.getId()));

		PageRequest pageRequest = new PageRequest(1, 10);
		pageRequest.setOrderBy("id");
		pageRequest.setOrderDir(PageRequest.Sort.DESC);
		Page<Message> messages = messageService.queryByUserIdAndType(
				pageRequest, user.getId(), Message.MessageType.CONTENT.type());
		model.addAttribute("messages", messages);

		return HtmlPathHelp.getHtmlPathFront("user_index");

	}

	@RequestMapping(value = "/member/index.html")
	public String memberIndex(HttpServletRequest request, ModelMap model) {
		int uid = WebUtil.getInt(request, "uid");
		User user = (User) userService.getUserById(uid);
		if (user == null) {
			return "redirect:/404.htm";
		}
		model.addAttribute("user", user);

		PageRequest jyPageRequest = new PageRequest(1, 5);
		jyPageRequest.setOrderBy("id");
		jyPageRequest.setOrderDir(PageRequest.Sort.DESC);
		Page<Jy> jys = jyService.queryJyByUserAndStatus(jyPageRequest, uid,
				STATUS_NORMAL.getState());
		model.addAttribute("jys", jys);

		PageRequest baoliaoPageRequest = new PageRequest(1, 5);
		baoliaoPageRequest.setOrderBy("id");
		baoliaoPageRequest.setOrderDir(PageRequest.Sort.DESC);
		Page<Baoliao> baoliaos = baoliaoService.queryBaoliaoByUserAndStatus(
				baoliaoPageRequest, uid, STATUS_NORMAL.getState());
		model.addAttribute("baoliaos", baoliaos);

		PageRequest pageRequest = new PageRequest(1, 5);
		pageRequest.setOrderBy("id");
		pageRequest.setOrderDir(PageRequest.Sort.DESC);
		Page<Message> messages = messageService.queryByUserIdAndType(
				pageRequest, user.getId(), Message.MessageType.CONTENT.type());
		model.addAttribute("messages", messages);

		List<Jy> limitJys = jyService.queryLimitJy(5);
		model.addAttribute("limitJys", limitJys);

		model.addAttribute("jyNum", jys.getTotalItems());
		model.addAttribute("baoliaoNum", baoliaos.getTotalItems());
		model.addAttribute("commentNum", messages.getTotalItems());

		return HtmlPathHelp.getHtmlPathFront("member_index");

	}

	@RequestMapping(value = "/member/jy.html")
	public String memberJy(HttpServletRequest request, ModelMap model) {
		int uid = WebUtil.getInt(request, "uid");
		User user = (User) userService.getUserById(uid);
		if (user == null) {
			return "redirect:/404.htm";
		}
		model.addAttribute("user", user);
		int pageNo = WebUtil.getInt(request, "pageNo", 1);
		int pageSize = WebUtil.getInt(request, "pageSize", 5);
		PageRequest jyPageRequest = new PageRequest(pageNo, pageSize);
		jyPageRequest.setOrderBy("id");
		jyPageRequest.setOrderDir(PageRequest.Sort.DESC);
		Page<Jy> jys = jyService.queryJyByUserAndStatus(jyPageRequest, uid,
				STATUS_NORMAL.getState());
		model.addAttribute("jys", jys);
		model.addAttribute("jyNum", jys.getTotalItems());
		model.addAttribute("baoliaoNum",
				baoliaoService.queryBaoliaoNumByUser(uid));
		model.addAttribute("commentNum",
				messageService.queryMessaageNumByUser(uid));
		model.addAttribute("jyCurrent", "current");
		List<Jy> limitJys = jyService.queryLimitJy(5);
		model.addAttribute("limitJys", limitJys);
		return HtmlPathHelp.getHtmlPathFront("member_jy");

	}

	@RequestMapping(value = "/member/baoliao.html")
	public String memberBaoliao(HttpServletRequest request, ModelMap model) {
		int uid = WebUtil.getInt(request, "uid");
		User user = (User) userService.getUserById(uid);
		if (user == null) {
			return "redirect:/404.htm";
		}
		model.addAttribute("user", user);
		int pageNo = WebUtil.getInt(request, "pageNo", 1);
		int pageSize = WebUtil.getInt(request, "pageSize", 5);
		PageRequest baoliaoPageRequest = new PageRequest(pageNo, pageSize);
		baoliaoPageRequest.setOrderBy("id");
		baoliaoPageRequest.setOrderDir(PageRequest.Sort.DESC);
		Page<Baoliao> baoliaos = baoliaoService.queryBaoliaoByUserAndStatus(
				baoliaoPageRequest, uid, STATUS_NORMAL.getState());
		model.addAttribute("baoliaos", baoliaos);
		model.addAttribute("baoliaoNum", baoliaos.getTotalItems());
		model.addAttribute("jyNum", jyService.queryNumByUser(uid));
		model.addAttribute("commentNum",
				messageService.queryMessaageNumByUser(uid));
		model.addAttribute("baoliaoCurrent", "current");
		List<Jy> limitJys = jyService.queryLimitJyByArea(5,
				Jy.Area.HTJY.getArea());
		model.addAttribute("limitJys", limitJys);
		return HtmlPathHelp.getHtmlPathFront("member_baoliao");

	}

	@RequestMapping(value = "/member/comment.html")
	public String memberComment(HttpServletRequest request, ModelMap model) {
		int uid = WebUtil.getInt(request, "uid");
		User user = (User) userService.getUserById(uid);
		if (user == null) {
			return "redirect:/404.htm";
		}
		model.addAttribute("user", user);
		int pageNo = WebUtil.getInt(request, "pageNo", 1);
		int pageSize = WebUtil.getInt(request, "pageSize", 5);
		PageRequest commentPageRequest = new PageRequest(pageNo, pageSize);
		commentPageRequest.setOrderBy("id");
		commentPageRequest.setOrderDir(PageRequest.Sort.DESC);
		int type = WebUtil.getInt(request, "t",
				Message.MessageType.CONTENT.type());
		Page<Message> messages = messageService.queryByUserIdAndType(
				commentPageRequest, uid, type);
		model.addAttribute("messages", messages);
		model.addAttribute("commentNum", messages.getTotalItems());
		model.addAttribute("jyNum", jyService.queryNumByUser(uid));
		model.addAttribute("baoliaoNum",
				baoliaoService.queryBaoliaoNumByUser(uid));
		model.addAttribute("commentCurrentUL", "curent_menu");
		if (type == Message.MessageType.CONTENT.type()) {
			model.addAttribute("commentCurrentLiContent", "subCurrent");
		} else if (type == Message.MessageType.FX.type()) {
			model.addAttribute("commentCurrentLiFx", "subCurrent");
		} else if (type == Message.MessageType.JY.type()) {
			model.addAttribute("commentCurrentLiJy", "subCurrent");
		}
		model.addAttribute("commentCurrent", "current");
		model.addAttribute("type", type);

		List<Jy> limitJys = jyService.queryLimitJyByArea(5,
				Jy.Area.HTJY.getArea());
		model.addAttribute("limitJys", limitJys);

		return HtmlPathHelp.getHtmlPathFront("member_comment");

	}

	@RequestMapping(value = "/login.html")
	@ResponseBody
	public String login(HttpServletRequest request, ModelMap model) {
		String username = WebUtil.getString(request, "username");
		String password = WebUtil.getString(request, "password");
		if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
			return "{\"result\":\"error\"}";
		}
		try {
			User user = new User();
			user.setUsername(username);
			user.setPassword(password);
			User dbUser = userService.login(user);
			if (dbUser != null) {
				WebUtils.setSessionAttribute(request, SESSION_USER, dbUser);
				return "{\"result\":\"ok\",\"username\":\""
						+ dbUser.getUsername() + "\",\"userid\":\""
						+ user.getId() + "\",\"usergrade\":\""
						+ dbUser.getGrade() + "\"}";
			}
		} catch (Exception e) {
			log.error("login error:" + e.getMessage());
		}

		return "{\"result\":\"error\"}";
	}

	@RequestMapping(value = "/register.html")
	public String reg(HttpServletRequest request, ModelMap model) {
		if (WebUtils.getSessionAttribute(request, SESSION_USER) != null) {
			return "redirect:/";
		}
		List<Fx> limitFxs = fxService.queryLimitFx(12);
		List<Coupon> limitCoupons = couponService.queryLimitCoupons(10);
		List<Jy> limitHaiTaoJys = jyService.queryLimitJyByArea(5,
				Jy.Area.HTJY.getArea());
		model.addAttribute("limitFxs", limitFxs);
		model.addAttribute("limitCoupons", limitCoupons);
		model.addAttribute("limitHaiTaoJys", limitHaiTaoJys);
		return HtmlPathHelp.getHtmlPathFront("register");
	}

	@RequestMapping(value = "/saveregister.html")
	public String savereg(@ModelAttribute("user") User user,
			HttpServletRequest request, ModelMap model) {
		if (StringUtils.isBlank(user.getUsername())) {
			model.addAttribute("error", "用户名不能为空!");
			return Constants.PAGE_PATH_500;
		}
		if (StringUtils.isBlank(user.getPassword())) {
			model.addAttribute("error", "密码不能为空!");
			return Constants.PAGE_PATH_500;
		}
		if (StringUtils.isBlank(user.getEmail())) {
			model.addAttribute("error", "邮箱不能为空!");
			return Constants.PAGE_PATH_500;
		}

		String reqCheckCode = WebUtil.getString(request, "checkcode");
		String sesCheckCode = (String) WebUtils.getSessionAttribute(request,
				SESSION_CHECKCODE);
		if (!StringUtils.equalsIgnoreCase(sesCheckCode, reqCheckCode)) {
			model.addAttribute("error", "验证码不正确，请重新输入!");
			return HtmlPathHelp.getHtmlPathFront("register");
		}
		user.setIssueTime(new Date());
		user.setStatus(STATUS_NORMAL.getState());
		user.setPoint(0);
		user.setAvatar("");
		try {
			userService.save(user);
			userService.operatePoint(user.getId(), OperatePoint.REG);
		} catch (Exception e) {
			model.addAttribute("error", "注册失败，请重试!");
			return HtmlPathHelp.getHtmlPathFront("register");
		}
		// 注册成功，把user存到session
		WebUtils.setSessionAttribute(request, SESSION_USER, user);
		return "redirect:/";
	}

	@RequestMapping(value = "/logout.html")
	public String logout(HttpServletRequest request, ModelMap model) {
		// 退出，把session中user置null
		WebUtils.setSessionAttribute(request, SESSION_USER, null);
		return "redirect:/";
	}

	@RequestMapping(value = "/checkusername.html")
	@ResponseBody
	public String checkUserName(HttpServletRequest request) {
		User user = userService.findUniqueBy("username",
				WebUtil.getString(request, "username"));
		if (user == null) {
			return "{\"result\":\"ok\"}";
		} else {
			return "{\"result\":\"no\"}";
		}
	}

	@RequestMapping(value = "/checkemail.html")
	@ResponseBody
	public String checkEmail(HttpServletRequest request) {
		User user = userService.findUniqueBy("email",
				WebUtil.getString(request, "email"));
		if (user == null) {
			return "{\"result\":\"ok\"}";
		} else {
			return "{\"result\":\"no\"}";
		}
	}

	@RequestMapping(value = "/getuser.html")
	@ResponseBody
	public String getUser(HttpServletRequest request) {
		User user = (User) WebUtils.getSessionAttribute(request, SESSION_USER);
		if (user != null) {
			return "{\"result\":\"ok\",\"username\":\"" + user.getUsername()
					+ "\",\"userid\":\"" + user.getId() + "\",\"usergrade\":\""
					+ user.getGrade() + "\"}";
		} else {
			return "{\"result\":\"no\"}";
		}
	}
}
